
/* $Log: Command.c,v $
/* Revision 1.23  2009/11/30 15:33:38  dimitrip
/* Added new command - SM ( Send SMS message )
/*
/* Revision 1.22  2009/11/11 09:20:42  dimitrip
/* Car Petrol Blocking update: if (registration > 2 min) reset;
/*
/* Revision 1.21  2009/11/03 10:54:21  dimitrip
/* Add "Car. Petrol Blocking" application
/*
/* Revision 1.20  2009/10/29 10:25:19  dimitrip
/* Add Print_SMS application
/*
/* Revision 1.19  2007/12/12 09:30:41  dimitrip
/* Add: Command Macro
/*
/* Revision 1.18  2007/12/10 09:08:47  dimitrip
/* *** empty log message ***
/*
/* Revision 1.17  2007/10/31 16:27:23  dimitrip
/* Add fews  command see CommandIterface.txt
/*
/* Revision 1.16  2007/10/29 16:59:23  dimitrip
/* *** empty log message ***
/*
/* Revision 1.15  2007/10/29 14:38:36  dimitrip
/* *** empty log message ***
/*
/* Revision 1.14  2007/10/05 18:31:56  Administrator
/* Implemented RF transmitter;
/* see RFT & RT command;
/*
/* Revision 1.13  2007/09/28 22:50:28  Administrator
/* RF Transmitter
/*
/* Revision 1.12  2007/09/25 17:11:40  dimitrip
/* *** empty log message ***
/*
/* Revision 1.11  2007/09/09 10:57:03  dimitrip
/* Add RF Remote, ARM mode;
/*
/* Revision 1.10  2007/08/26 16:54:05  dimitrip
/* *** empty log message ***
/*
/* Revision 1.9  2007/08/26 16:06:25  dimitrip
/* RF - OK;
/*
/* Revision 1.8  2007/04/06 13:14:04  dimitrip
/* 1. Check hardware of new board;
/* 2. Integration of MOTOROLA G24 modem;
/*
/* Revision 1.7  2007/02/05 12:30:39  dimitrip
/* *** empty log message ***
/*
/* Revision 1.8  2007/01/09 17:08:21  dimitrip
/* *** empty log message ***
/*
/* Revision 1.6  2006/12/28 16:10:07  dimitrip
/* *** empty log message ***
/*
/* Revision 1.5  2006/12/21 16:13:25  dimitrip
/* *** empty log message ***
/*
/* Revision 1.4  2006/12/17 17:00:07  dimitrip
/* *** empty log message ***
/*
/* Revision 1.3  2006/12/14 15:58:22  dimitrip
/* *** empty log message ***
/*
/* Revision 1.2  2006/12/07 16:24:44  dimitrip
/* *** empty log message ***
/* */

//#include "main.h" 
#include "ex_eeprom.h"
#include "printf.h"
#include "Print.h"
#include "Command.h"
#include "my_macros.h"
#include "Application.h"
#include "string.h"
#include "ModemService.h"
#include "USART.h"
//#include "DataMode.h"
#include "eeprom.h"
#include "FUpdate.h"
#include "Config.h"
#include "Passwords.h"
#include "Status.h"
#include "Analog.h"
#include "AuxPort.h"
#include "PhoneNumbers.h"
#include "ex_eeprom.h"
#include "Debug.h"
#include "InputsHandlers.h"
#include "Consts.h"
#include "RF_Manager.h"
#include "hardware.h"
#include "Outputs.h"
#include "CmdMacros.h"
#include "NeighborCells.h"
#include "SysTime.h"
#include "Tools.h"
#include "Receivers.h"


extern const char	STR__OK[];
extern unsigned char RF_Tx_Buffer[];
extern volatile near bit RF_TX_START;

/* #include <pic18.h> */
/* #include "printf.h" */
/* #include "Application.h" */
/* #include "my_macros.h" */
/* #include "Command.h" */
/* #include "Print.h" */
/* #include "string.h" */
/* #include "ModemService.h" */
/* #include "Sys_Strings.h" */
/* #include "USART.h" */
/* #include "Passwords.h" */
/* #include "DataMode.h" */
/* #include "eeprom.h" */
/* #include "FUpdate.h" */
/* #include "Config.h" */
/* #include "Status.h" */
/* #include "Analog.h" */
/* #include "AuxPort.h" */
/* #include "PhoneNumbers.h" */
/* #include "ex_eeprom.h" */
/* #include "Debug.h" */
/* #include "InputsHandlers.h" */

/* NOTE: Each Command must be start in this format ##xxxx. ,where  '##' is Command Token, xxxx - Password and point - end
 of Command. 
 Password maybe contains any characters, exclude ' ' '.' (space and point)  */

unsigned char Sys_Command_Buffer[SYS_COMMAND_BUFFER_SIZE];
unsigned char Login_Of_UserName[20]; 
near bit SYS_COMMAND, LG_LOGIN_OF_USER;

unsigned char SMS_Commands[SMS_COMMANDS_QUEUE_MAX];
unsigned char pSMS_Commands = 0;
unsigned char RC_PressedKey;	  /* Remote Control */

unsigned char str[70];
unsigned char str_2[18];
unsigned char SMS_To_Delete = 0;

bit DO_RESET;

near bit UserInList, CmdException;

unsigned int Message_ID = 0;	  /* Random value - use as label for Set Date and Time */

unsigned char* Command_Line;

unsigned char CommandSource = 0;
unsigned char CommandHandler__Error;

/* for debug */
unsigned char ds[6];
/*  */

unsigned char sBCD[8];

FUNCTION* Special;

#define   TEMP_STRING_SIZE		48
unsigned char g_t_str[TEMP_STRING_SIZE];

//void (*Execute_Module_1) (void) ;

//COMMAND_LINE bank1 CommandLine;

COMMAND_HEADER CommandHeader;

SMS_PACKET_RECEIVE SMS_Packet_Receive;

//#define   MESSAGE_FLAG	SMS_Pac

unsigned char DefineAndExecuteCommand ( unsigned char* ComLine );


void Cmd_Return ( void )
{
	Execute_Module_1 = Command_Processor;
}

enum
{
/* 	ST__SET_DATE_AND_TIME = 0, */
/* 	SH__SET_APPARATUS_PHONE_NUMBER,	  /\* telephone number *\/ */

	NA__ADD_NUMBER,				  /* NA0 - add to OWNERS NA1 - add to USER */
	ND__DELETE_NUMBER,
	LD__DELETE_LIST,				  /* delete list of OWNERRs or of USERs */
	IS__SET_INPUT,					  /* Set description of the Input; /what do if the Input state was change/ */
	ID__DELETE_INPUT,				  /* Delete description of the Input */
	HD__HANDSHAKE,					  /* ## */
/* 	GC__GET_CDR, */
	ES__END_OF_SESSION,
	//SV__SWITCH_VERSION, 
	SU__SOFTWARE_UPDATE,
	
	CB__SET_CONFIG_BITS,
	GS__GET_STATUS_FILE,
	RF__RF_REMOTE_LEARNE_MODE,
	RT__RF_TRANSMIT,
	SL__SHOW_LIST,
	IF__SET_RF_INPUT,				  /* scenario for event of RF input */
	TE__TECHNICAL_COMMANDS,
	OS__SET_OUTPUTS,
	MS__SET_MACROS,
	NC__NEIGHBOR_CELLS,
	LG__LOGIN_TO_PHONE,
	AE__ADD_COMMAND_EXCEPTION, /*this command - add command that will be execute by SMS without any password- dangerous! */
	SM__SEND_SMS_MESSAGE,
	SP__SEND_TO_PORT,
	
/* 	NP__SET_NMS_PHONE_LIST, */
/* 	AI__ADD_IMSI_RANGE, */
/* 	SI__SET_IMSI_RANGE, */
/* 	SM__SET_INTERNAL_IMSI, */
/* 	GM__GET_INTERNAL_IMSI, */
	/* Passwords Commands */
/* 	PO_SET_PASSWORD_OWNER, */
/* 	PM_SET_PASSWORD_MASTER, */
/* 	PI_SET_PASSWORD_INSTALLER, */

	/* Remote Control */
/* 	KE__SEND_KEY, */
/* 	DO__DISPLAY_ON, */
/* 	DF__DISPLAY_OFF, */
	
	/*  */
	CC__COMMANDS_COUNT
};

int ExeSysCommand ( const unsigned char *Command )
{
	if ( Execute_Module_1 == NULL )
	{

		if ( StrLen(Command) > 0 && StrLen(Command) < SYS_COMMAND_BUFFER_SIZE )
		{
			StrCpy(Sys_Command_Buffer, Command);
			SYS_COMMAND = TRUE;
			Execute_Module_1 = Command_Processor;
			return TRUE;
		}
		else
		{
			return -2;
		}
	} 


	return -1;
}


void SMS_Command_Delete ( void )
{
	static unsigned char State = 0, ErrCnt = 0;
	unsigned char Response;

	switch ( State )
	{
		case 0:
			if ( SMS_To_Delete == 0 )
			{
				Execute_Module_1 = NULL;
				return;
			}
			else
			{
				State++;
			}
			break;

		case 1:
			StrCpy( str, "AT+CMGD=" );
			LongToStr((str+errno), (unsigned long)SMS_To_Delete );
			StrCat( str, "\r");
			State++;
			ErrCnt = 8;
			break;

		case 2:
			
			Response = SendToModem( str, STR__OK, BUSY_SMS_COMMAND_DELETE );
			
			if ( Response != BUSY )
			{
				//lcd_clear_str(0,1);
				//putsf("  **********> BD \r", MODEM_PORT);
				if ( Response == TRUE )
				{
					putsf(" > DEL__OK \r", MODEM_PORT);
					Execute_Module_1 = Command_Processor;
					State = 0;
				}
				else
				{
					if ( ErrCnt == 0 )
					{
						//putsf("  **********> BD == END \r", MODEM_PORT);
						Execute_Module_1 = Command_Processor;
						State = 0;
					}
					else
					{
						//putsf("  **********> BD == FALSE \r", MODEM_PORT);
						ErrCnt--;
						//putsf("AT\r", MODEM_PORT );
						//delay_ms(200);
					}
				}
			}

			break;
			

		default :
			;
	}
} 

/* Handshake */
/* void CommandHandler_HD( void ) */
/* { */
/* 	unsigned char Password[5]; */

/* 	Execute_Module_1 = Command_Processor; */

/* 	Password_Generator( Password, ListCurrentCalls.PhoneNumber ); */

/* /\* 	lcd_clear_str(3,2); *\/ */
/* /\* 	lcd_puts(Password); *\/ */
/* /\* 	lcd_putchar(' '); *\/ */
/* /\* 	lcd_puts(Command_Line+2); *\/ */

/* 	if ( StrCmp(Password, Command_Line+2) == 0 )   */
/* 	{ */
/* 		StrCpy(ACK,"NX"); */
/* 	} */
/* 	else */
/* 	{ */
/* 		StrCpy(ACK,"ER02");		  /\* password is WRONG *\/ */
/* 	} */

/* 	DataMode_Transmitter(ACK, 0); */
/* } */
  

/* End of Session */
void CommandHandler_ES( void )
{
	Execute_Module_1 = Command_Processor;
  	//Send_ACK("NX");
	//DataModeTimeout = 2;
}

/* Software Update */
void CommandHandler_SU( void )
{
	GIE = FALSE;  // disable all interrupt
	/* e2_Write(E2_ADDR_BOOT_STATUS, BOOT_FROM_MODEM); */
	/* //TXSTA1 = 0; */
	/* delay_ms(100); */

	RESET();
}
 
/* Set Configuration Bits */
void 	CommandHandler_CB( void )
{
	Execute_Module_1 = Command_Processor;
	CharToHex((unsigned char*)&ConfigFile, (Command_Line + 2) );
	Config_Write();
	PrevState = 0;
}

void SMS_CreateHeader( unsigned char* Message, unsigned char* DestinationPhone )
{
	StrCpy( str, "AT+CMGS=\"");
	StrCat( Message, DestinationPhone);
	if ( DestinationPhone[0] == '+' )
		StrCat( Message, "\",145\r" ); 
	else
		StrCat( Message, "\",129\r"); 
	
	StrCat( Message, "##");		  /* Command Token */
	E2_Str_LoadFrom(PhoneNumber, E2_ADDR_MY_PHONE_NUMBER);
	Password_Generator( str_2, PhoneNumber );
	StrCat( Message, str_2);

	E2_Str_LoadFrom(str_2, E2_ADDR_MY_IMEI_NUMBER);
	StrCat( Message, str_2);
}
 
unsigned char SendStatus( unsigned char* DestinationPhone  )
{
	static unsigned char State = 0;//, str[70];
	unsigned char Response;
		  
	if ( State == 1 )
		goto SEND_STATUS;

	if ( State == 2 )
		goto WAIT_FOR_MODEM;

	Response = SendToModem( "AT+CCLK?\r", STR__OK, BUSY_SEND_STATUS );
	if ( Response != BUSY )
	{
		if ( Response == TRUE )
		{
			//StatusFile.DateTime = TimePackage( ModemRecBuffer );
			State++;
		}
		else
		{
			//delay_ms(100);
			return BUSY; 					  /* try again */
		}
	}
	else
	{
		return BUSY;
	}
	
  SEND_STATUS:
	
	StatusFile.ConfigFile = ConfigFile;
	StatusFile.StatusBits = StatusBits;
	//StatusFile.CDR_Index = CDR_AddressToIndex(CDR_Pointer);
	StatusFile.RSSI = RSSI;
	StatusFile.Battery = ATD_Result; 

	if ( CommandSource == AUX_PORT )
	{
		E2_Str_LoadFrom(str, E2_ADDR_MY_IMEI_NUMBER);
		puts(str, AUX_PORT);
		putsf("SS", AUX_PORT);
		HexToChar(str, (unsigned char*)&StatusFile, sizeof(STATUS_FILE) );
		puts(str, AUX_PORT);
		putsf( Revision_Basic+11, AUX_PORT);
		putch('\r', AUX_PORT);
		State = 0;
		//Execute_Module_1 = Command_Processor;
		return TRUE;
	}


	SMS_CreateHeader(str, DestinationPhone);
	StrCat(str, "SS");
	//HexToChar(str_2, (unsigned char*)&StatusFile, sizeof(STATUS_FILE) );
	HexToChar(&str[StrLen(str)], (unsigned char*)&StatusFile, sizeof(STATUS_FILE) );
	//StrCat(str, str_2);
	StrCat(str, (Revision_Basic+11));
	StrCat(str, "\x1A");
	
	State++;
	return BUSY;

  WAIT_FOR_MODEM:
	Response = SendToModem(str, STR__OK, BUSY_SEND_STATUS) ;
	if ( Response != BUSY )
	{
		State = 0;			  

		if ( Response == TRUE )
		{
			//Execute_Module_1 = Command_Processor;
			return TRUE;
		}
		else
		{
			return FALSE; /* try again */
		}
		
	}

	return BUSY;
	//##187B359811000013737SS7A884A0D2904000000000000A300504100001.40 $
   //      359811000013737SSD4884A0D2904000000000000A3004D4300001.40 $

}
 
void Send_Event( void )
{
	if ( SendStatus( NMS_PhoneNumber ) == TRUE )
	{
		Execute_Module_1 = NULL;
	}
}

/* Get Status File */
void CommandHandler_GS ( void )
{
	if ( SendStatus( SMS_Header.Field.PhoneNumber ) == TRUE )
	{
		Execute_Module_1 = Command_Processor;
	}
}
 


/* Remote Control. Set Key */
/* void CommandHandler_KE( void ) */
/* { */
/* //	unsigned char Buf[90]; */
/* //	ClearBuffer(Buf,90); */

/* 	Execute_Module_1 = Command_Processor; */

/* 	//lcd_print_str(Command_Line, 7,2,0); */

/* 	if ( Command_Line[2] == 'H' )	/\* HOOK_ON, HOOK_OFF *\/ */
/* 	{ */
/* 		PIN_HOOK ^= 1; */
/* 		PIN_HOOK_DIR = OUTPUT; */
/* 	} */
/* 	else */
/* 		if ( Command_Line[2] == 'X' )	/\* Release HOOK *\/ */
/* 		{ */
/* 			PIN_HOOK_DIR = INPUT; */
/* 		} */
/* 		else */
/* 			if ( Command_Line[2] == 'D' ) */
/* 			{ */
/* 				DISPLAY_ON ^= TRUE; */
/* 				Ext_Display_Update(); */
/* 			} */
/* 			else */
/* 			{ */
/* 				RC_PressedKey = Command_Line[2]; */
/* 			} */
/* } */
/* Remote Control. Display ON */
 
/* void CommandHandler_DO( void ) */
/* { */
/* 	DISPLAY_ON = TRUE; */
/* 	Execute_Module_1 = Command_Processor; */
/* } */

/* /\* Display OFF *\/  */
/* void CommandHandler_DF( void ) */
/* { */
/* 	DISPLAY_ON = FALSE; */
/* 	Execute_Module_1 = Command_Processor; */
/* } */
/* /\* END of Remote Control *\/ */

/* Add Customer Entry (Phone Number)  */
void CommandHandler_NA ( void )
{
/* 	signed int EOL;							  /\* End Of Line *\/ */
/* 	unsigned char p = 3;//, pp; */

	unsigned int List;
	unsigned char * pData;
	unsigned char len;
	RECORD_CUSTOMER CustomerRecord;

//
	int Address;						  /* For Debug ONLY! */
//
	Execute_Module_1 = Command_Processor;

	//putsf(">>NA\r", MODEM_PORT);
	List = ListNumber_ToAddress(Command_Line[2] - '0' );
	
	if ( List == UNKNOWN_GROUP )
	{
		Debug("NA: LIST ERROR\r");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		return ;
	}

/* 	while(1) */
/* 	{ */
/* 		EOL = StrReplaceChar(Command_Line+p, ' ', 0); */
/* 		//pp = errno; */

/* 		StrToBCD(CustomerRecord.Phone, Command_Line+p, sizeof(CustomerRecord.Phone) ); */
/* 		FlipFlopN(CustomerRecord.Phone, sizeof(CustomerRecord.Phone) ); */
/* 		CustomerRecord.Reserve = 0xFF; */
		
/* 		Address = Ex_Entry_Write(List, (unsigned char*)&CustomerRecord); */
/* 		if ( Address == EX_ERROR ) */
/* 		{ */
/* 			Debug("\rEEPROM ADDRESS: ERROR ", Address ); */
/* 			return ; */
/* 		} */
		
/* 		Debug("\rEEPROM ADDRESS: ", Address ); */
  
/* 		//CR_Add(List, Command_Line+p);	/\* Add customer *\/ */
/* 		if ( EOL == (-1) )		/\* if EOL == -1 then it's end of CommandLine ( next Phone not found) *\/  */
/* 			return ; */
/* 		p += ++EOL; */
/* 	} */

	pData = &Command_Line[3];

	for(;;)
	{
		/* get Phone number of User */

		if ( pData )
		{
			pData = StrCpy_UpTo_Ch(g_t_str, pData, ' ');
			Debug("\ng_t_str: [%s]\n", g_t_str);
		}
		else
		{
			Debug("\nNA: End of command\n");
			return ;
		}
		
		
		if ( StrLen(g_t_str) > 0 )
		{
			StrToBCD(CustomerRecord.Phone, g_t_str, sizeof(CustomerRecord.Phone) );
			FlipFlopN(CustomerRecord.Phone, sizeof(CustomerRecord.Phone) );
		}
		else
		{
			Debug("\rNA: user phone ERROR (str_len = %d)", StrLen(g_t_str));
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		CustomerRecord.Reserve = 0xFF;

		/* get password of User */
		/* if ( pData ) */
		/* {  */
		/* 	pData = StrCpy_UpTo_Ch(g_t_str, pData, ' '); */
		/* } */
		/* else */
		/* { */
		/* 	Debug("\rNA: user password - ERROR ");	/\* password not found *\/ */
		/* 	CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA; */
		/* 	return ; */
		/* } */
		
		/* len = StrLen(g_t_str); */

		/* if ( len > 0 && len < (unsigned char)sizeof(CustomerRecord.UserPassword) ) */
		/* { */
		/* 	StrCpy(CustomerRecord.UserPassword, g_t_str); */
		/* } */
		/* else */
		/* { */
		/* 	Debug("\rNA: password len - ERROR");	/\* password not found *\/ */
		/* 	CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA; */
		/* 	return; */
		/* } */
		CustomerRecord.UserPassword[0] = 0;

		/* Save data */
		Address = Ex_Entry_Write(List, (unsigned char*)&CustomerRecord);
		if ( Address == EX_ERROR )
		{
			Debug("\nNA: EEPROM ADDRESS: ERROR - 0x%X", Address );
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		Debug("\nNA: EEPROM ADDRESS: 0x%X", Address );

	}
}

/* Delete List */
void CommandHandler_LD ( void )
{
	unsigned int List;

	Execute_Module_1 = Command_Processor;
	
	if ( Command_Line[2] == 'A')
	{
		Ex_Entry_DeleteDirectory(LIST_OWNERS);
		Ex_Entry_DeleteDirectory(LIST_USERS_GROUP_1);
		Ex_Entry_DeleteDirectory(LIST_USERS_GROUP_2);
		Ex_Entry_DeleteDirectory(LIST_USERS_GROUP_3);
		Ex_Entry_DeleteDirectory(LIST_USERS_GROUP_4);
		Ex_Entry_DeleteDirectory(LIST_INPUTS_DESCRIPTORS);
		return;
	}

	List = ListNumber_ToAddress(Command_Line[2] - '0' );

	if ( List == UNKNOWN_GROUP )
	{
		putsf("\r Delete List: LDn where n is:\r0-OWNERS\r1-USERS_GRP_1\r2-USERS_GRP_2\r3-USERS_GRP_3", AUX_PORT);
		putsf("\r4-USERS_GRP_4\r5-Input Descriptors List\rA-delete all\r", AUX_PORT);
	}
	else
	{
		Ex_Entry_DeleteDirectory(List);
	}

/* 	if ( Command_Line[2] == '0' )	/\* 0 - OWNERS LIST; 1 - USERS LIST; 2 - LIST_INPUTS_DESCRIPTORS *\/ */
/* 	{ */
/* 		List = LIST_OWNERS; */
/* 	} */
/* 	else */
/* 		if ( Command_Line[2] == '1') */
/* 		{ */
/* 			List = LIST_USERS_GROUP_1; */
/* 		} */
/* 		else */
/* 			if ( Command_Line[2] == '2' ) */
/* 			{ */
/* 				List = LIST_INPUTS_DESCRIPTORS; */
/* 			}		   */
/* 			else */
/* 			{ */
/* 				Ex_Entry_DeleteDirectory(LIST_OWNERS); */
/* 				Ex_Entry_DeleteDirectory(LIST_USERS_GROUP_1); */
/* 				Ex_Entry_DeleteDirectory(LIST_INPUTS_DESCRIPTORS); */
/* 				return ; */
/* 			}	 */

/* 	Ex_Entry_DeleteDirectory(List); */
}

void CommandHandler_ND( void )
{
	int EOL;							  /* End Of Line */
	unsigned int List;
	unsigned char p = 3;//, pp;
	RECORD_CUSTOMER CustomerRecord;

//
	int Address;						  /* For Debug ONLY! */
//

	Execute_Module_1 = Command_Processor;

//	putsf(">>NA\r", MODEM_PORT);

	List = ListNumber_ToAddress(Command_Line[2] - '0' );

	if ( List == UNKNOWN_GROUP )
	{
		putsf("\rDelete Number: NDn PH  where n=0 OWNERS, n=1 USERS. PH - phone number\r", AUX_PORT);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		return ;
	}


/* 	if ( Command_Line[2] == '0' )	/\* 0 - Owlers List; 1 - Users List *\/ */
/* 	{ */
/* 		List = LIST_OWNERS; */
/* 	} */
/* 	else */
/* 		if ( Command_Line[2] == '1' )	 */
/* 		{ */
/* 			List = LIST_USERS_GROUP_1; */
/* 		} */
/* 		else */
/* 		{ */
/* 			//Debug(">> LIST ERROR\r", 0); */
/* 			putsf("\rDelete Number: NDn PH  where n=0 OWNERS, n=1 USERS. PH - phone number\r", AUX_PORT); */
/* 			return ; */
/* 		} */
	
	//NA00523974963 0525620534 0523905274|0|
	while(1)
	{
		EOL = StrReplaceChar(Command_Line+p, ' ', 0);
		//pp = errno;

		StrToBCD(CustomerRecord.Phone, Command_Line+p, sizeof(CustomerRecord.Phone) );
		FlipFlopN(CustomerRecord.Phone, sizeof(CustomerRecord.Phone) );
		//CustomerRecord.Reserve = 0xFF;
		
		//Address = Ex_Entry_Write(List, (unsigned char*)&CustomerRecord);
		Address = Ex_Entry_Delete(List, (unsigned char*)&CustomerRecord);
		
		if ( Address == EX_ERROR )
		{
			Debug("ND: EEPROM ADDRESS (0x%X): NOT FOUND ", Address );
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		Debug("ND: EEPROM ADDRESS: 0x%X", Address );
  
		//CR_Add(List, Command_Line+p);	/* Add customer */
		if ( EOL == (-1) )		/* if EOL == -1 then it's end of CommandLine ( next Phone not found) */ 
			return ;
		p += ++EOL;
	}
}

/* Set(Add) Inputs descriptor */
void CommandHandler_IS ( void )
{
	unsigned int Address;
	unsigned char *pComLine, i;
	INPUTS_DESCRIPTOR InpDes;
 
//typedef struct
//{
//		unsigned char InputName;  		/* Input number */
//		unsigned char EventsOnEdge; 	/* RISE or FALL or PULSE*/
//		unsigned long Reserve;
//		unsigned char Message[30];
//		
//}INPUTS_DESCRIPTOR;				  /* Input event descriptor */

//	IS10 200 0 Alarm of pulse 2Sec$
	
	Execute_Module_1 = Command_Processor;

	pComLine = Command_Line+2;

	/* Inputs Name */
	InpDes.InputName = StrToLong(pComLine);
	//pComLine = FindChar(pComLine, ' ');
	pComLine += errno;
	//pComLine++;						  /* next field (value) */
	
	/* Edge Alarm */
	InpDes.EventsOnEdge = StrToLong(pComLine);
	//pComLine = FindChar(pComLine, ' ');
	//pComLine++;						  /* next field (value) */
	pComLine += errno;

	/* Reserv */
	InpDes.Reserve = StrToLong(pComLine);
	//pComLine = FindChar(pComLine, ' ');
	//pComLine++;
	pComLine += errno;

/* 	if ( StrLen(pComLine) > INPUTS_DESCRIPTOR_MESSAGE_SIZE ) */
/* 		pComLine[INPUTS_DESCRIPTOR_MESSAGE_SIZE+1] = 0; */
/* 	StrCpy(InpDes.Message, pComLine); */
	
	//[1]
	
	//Dima for ( i = 0; i < INPUTS_DESCRIPTOR_MESSAGE_SIZE; i++ )
	for ( i = 0; i < INPUTS_DESCRIPTOR_MESSAGES_COUNT; i++ )
	{
		pComLine = StrCpy_UpTo_Ch(str, pComLine, ';'); /* message for groups */

		if ( StrLen(str) > INPUTS_DESCRIPTOR_MESSAGE_SIZE )
			str[INPUTS_DESCRIPTOR_MESSAGE_SIZE+1] = 0;
		
		StrCpy(InpDes.Message[i], str);
	
		if ( pComLine == NULL )
		{
			break;
		}
	}

	dbg("LIST_INPUTS_DESCRIPTORS: 0x%X", LIST_INPUTS_DESCRIPTORS); //Dima
	
	Address = Ex_Entry_Write(LIST_INPUTS_DESCRIPTORS, (unsigned char*)&InpDes);
	
	if ( Address != EX_ERROR )
	{
		Debug("\nEEPROM ADDRESS: 0x%X\n", Address);
		CommandHandler__Error = 0;
	}
	else
	{
		Debug("\nIS: EEPROM ADDRESS (0x%X): ERROR\n", Address);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

/* void Delete_Entry ( unsigned int List, unsigned char* EntryName ) */
/* { */
/* 	switch (  List ) */
/* 	{ */
/* 		case 0: */
			
/* 			break; */

/* 		case 1: */

/* 			break; */
			
/* 		case 3: */

/* 			break; */

/* 		default: */
/* 			; */
/* 	} */


/* } */
/* Input delete */
void CommandHandler_ID ( void )
{
	int EOL;							  /* End Of Line */
	//unsigned int List;
	unsigned char p = 2;//, pp;
	signed char InputName;
	int Address;						  /* For Debug ONLY! */

	Execute_Module_1 = Command_Processor;

	while(1)
	{
		EOL = StrReplaceChar(Command_Line+p, ' ', 0);
	
		InputName = StrToLong(Command_Line+p);
	
		if ( InputName > 0 )
		{
			Address = Ex_Entry_Delete(LIST_INPUTS_DESCRIPTORS, (unsigned char*)&InputName);
		
			if ( Address == EX_ERROR )
			{
				Debug("\nID: EEPROM ADDRESS (0x%X): NOT FOUND\n", Address );
				//return ;
			}
			else
				Debug(">>EEPROM ADDRESS: 0x%X\n", Address );
		}

		if ( EOL == (-1) )		/* if EOL == -1 then it's end of CommandLine ( next Phone not found) */ 
		{
			//CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}

		p += ++EOL;
	}
}

void CommandHandler_RF ( void )
{
	Execute_Module_1 = Command_Processor;
	

	if ( SysState == IDLE )
	{
		if ( Command_Line[2] == 'T' )
		{
			RF_LearnParameters = RF_REMOTE_TRANSMIT;
			putsf("\r ====== RF LEARN MODE (as transmitter) =======", AUX_PORT );
		}
		else
		{
			putsf("\r ================ RF LEARN MODE ==============", AUX_PORT );
		}
		SysState = RF_LEARN_MODE;

	}
	else
	{
		//putsf("\r ERROR: SysState is not IDLE;", AUX_PORT);
		Debug("\nRF: ERROR - SysState(%d) is not IDLE\r", SysState);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

/* void CommandHandler_SL ( void ) */
/* { */
/* 	unsigned int List; */

/* 	Execute_Module_1 = Command_Processor; */

/* 	List = ListNumber_ToAddress(Command_Line[2] -'0'); */
	
/* 	if ( List == UNKNOWN_GROUP ) */
/* 	{ */
/* 		putsf("\rShowList: SLn where n=0 for OWNER; n=1 for USERS\r", CommandSource); */
/* 		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA; */
/* 	} */
/* 	else */
/* 	{ */
/* 		Ex_Show_List( List, CommandSource ); */
/* 	}  */

/* /\* 	if( Command_Line[2] == '0' ) *\/ */
/* /\* 	{ *\/ */
/* /\* 		Ex_Show_List( LIST_OWNERS, CommandSource ); *\/ */
/* /\* 	} *\/ */
/* /\* 	else *\/ */
/* /\* 		if ( Command_Line[2] == '1' ) *\/ */
/* /\* 		{ *\/ */
/* /\* 			Ex_Show_List( LIST_USERS_GROUP_1, CommandSource );  *\/ */
/* /\* 		} *\/ */
/* /\* 		else *\/ */
/* /\* 		{ *\/ */
/* /\* 			putsf("\rShowList: SLn where n=0 for OWNER; n=1 for USERS\r", CommandSource); *\/ */
/* /\* 		} *\/ */
/* } */
/* 
Example:
IF4 1 300 PANIC: Haim Ozer 12/2 Ramatgan$
Button - 4; Output 1 do pulse 30sec (300x100ms) send SMS message PANIC: ....
 */
void CommandHandler_IF ( void )
{
	unsigned char *pComLine, i;
	unsigned int Address;
	RF_INPUT_DESCRIPTOR RF_Input_Descriptor; 

	Execute_Module_1 = Command_Processor;

	pComLine = Command_Line;

	/* RF Button */
	RF_Input_Descriptor.Button = StrToLong(pComLine);
	pComLine += errno;
	
	/* Output number */
	RF_Input_Descriptor.OutputNumber = StrToLong(pComLine);
	pComLine += errno;

	/* Output type: LOW(0), HIGH(1), PULSE(>1)  */
	RF_Input_Descriptor.OutputType = StrToLong(pComLine);
	pComLine += errno;
	
/* 	if ( StrLen(pComLine) > RF_INPUT_MESSAGE_SIZE ) */
/* 		pComLine[RF_INPUT_MESSAGE_SIZE+1] = 0; */
		
/* 	StrCpy(RF_Input_Descriptor.Message, pComLine); */

	for ( i = 0; i < RF_INPUT_DESCRIPTOR_MESSAGES_COUNT; i++ )
	{
		pComLine = StrCpy_UpTo_Ch(str, pComLine, ';'); /* message for OWNERS group */

		if ( StrLen(str) > INPUTS_DESCRIPTOR_MESSAGE_SIZE )
			str[INPUTS_DESCRIPTOR_MESSAGE_SIZE+1] = 0;
		
		StrCpy(RF_Input_Descriptor.Message[i], str);

		Debug("\nRF_Input_Descriptor.Message[%d] = %s", i, RF_Input_Descriptor.Message[i]);
		
		if ( pComLine == NULL )
		{
			break;
		}
	}

	
	Address = Ex_Entry_Write(LIST_RF_INPUTS_DESCRIPTORS, (unsigned char*)&RF_Input_Descriptor);
	
	if ( Address != EX_ERROR )
	{
		Debug("\nEEPROM ADDRESS: 0x%X", Address);
	}
	else
	{
		Debug("\nIF: ERROR - EEPROM ADDRESS (0x%X)", Address);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

void SysReset ( void )
{
	PIN_MODEM_POWER = 0;
	delay_ms(1000);
	RESET();
}

void CommandHandler_TE ( void )
{
	unsigned char str[30], Result;
	Execute_Module_1 = Command_Processor;

	switch ( Command_Line[2] )
	{
		case 'D':
			if ( Command_Line[3] == '0' )
			{ 
				DebugOut_Enable = FALSE;
			}
			else
			{
				DebugOut_Enable = TRUE;
			}
			break;

		case 'X':
			Ex_ClearAll();
			putsf("\rDeleted\r>> Restart", AUX_PORT);
			SysReset();
			break;

		case 'I':
			E2_Delete(1, 1023);
			putsf("\rDeleted\r>> Restart", AUX_PORT);
			SysReset();
			break;

		case 'R':
			SysReset();
			break;

		case 'S':					  /* SIM operation */
			switch( Command_Line[3] )
			{
				case 'U':			  /* Unlock */
					StrCpy(str, "AT+CLCK=\"SC\",0,");
					break;

				case 'L':
					StrCpy(str, "AT+CLCK=\"SC\",1,");
					
					break;

				case 'C':			  /* Change password */
					StrCpy(str, "AT+CPWD=\"SC\",");
					break;

				default:
					putsf("\rSIM - Unlock: TESU\"password\"\rSIM - Lock: TESL\"password\"", AUX_PORT);
					putsf("\rSIM - Change Password: TESC\"old-password\",\"new-password\"\r", AUX_PORT);
					return;
			}
			
			StrCat(str, &Command_Line[4]); 
			StrCat(str,"\r"); 
			Result = SendToModem(str, STR__OK, BUSY_TE_SIM_OPERATION); 
			if ( Result != BUSY )
			{
				putch('\r', AUX_PORT);
				if ( Result == TRUE )
					putsf("OK\r", AUX_PORT);
				else
					putsf("ERROR\r", AUX_PORT);
			}
			else	
				Execute_Module_1 = CommandHandler_TE;
			return;
		default:
				putsf("> TEX - Delete all external EEPROM\r", AUX_PORT);
				putsf("> TEI - Delete all internal EEPROM\r", AUX_PORT);
				putsf("> TER - Restart\r", AUX_PORT);
				putsf("> TES - SIM operations\r", AUX_PORT);	
				putsf("> TED - Debug output ON/OFF (0/1)\r", AUX_PORT);	
		
			return;
	}

}
 
void CommandHandler_OS ( void )
{
	unsigned char Offset = 2;
	signed int tmp;

	Execute_Module_1 = Command_Processor;

	tmp = StrToLong(&Command_Line[Offset]);
	if ( tmp != -1 )
	{
		if ( tmp >= 0 )
			OUT_1 = tmp;
	}
	else
		return;
	Offset += errno; 

	tmp = StrToLong(&Command_Line[Offset]);
	if ( tmp != -1 )
	{
		if ( tmp >= 0 )
			OUT_2 = tmp;
	}
	else
		return;
	Offset += errno; 

	tmp = StrToLong(&Command_Line[Offset]);
	if ( tmp != -1 )
	{
		if ( tmp >= 0 )
			OUT_3 = tmp;
	}
	else
		return;
	Offset += errno; 

	tmp = StrToLong(&Command_Line[Offset]);
	if ( tmp != -1 )
	{
		if ( tmp >= 0 )
			OUT_4 = tmp;
	}

}

void CommandHandler_RT ( void )
{
	static unsigned char Times, State = 0, i = 0;
	int Errors;
	RECORD_RF_REMOTE Received_RF_Remote;

	switch ( State )
	{
		case 0:
			
	  FIND:		
			Errors = Ex_Entry_Read_ByIndex(LIST_RF_REMOTE, (unsigned char*)&Received_RF_Remote, i++); 
			if ( Errors != EX_ERROR )	
			{
				if ( Errors != EX_ERROR__INDEX_IS_EMPTY && Received_RF_Remote.Special.Transmit == TRUE )
				{
					MemCpy(RF_Tx_Buffer, (unsigned char*)&Received_RF_Remote, 3);
					Times = 20;
					State++;
				}
				else
					goto FIND;
			}
			else
			{
				Debug("\rEnd of RF Remote Transmit");
				i = 0;
				Execute_Module_1 = Command_Processor;
				return; 
			}

		case 1:
			RF_TX_START = TRUE;
			PIN_RF_TX_ENABLE = TRUE;
			State++;
			break;
			
		case 2:
			if ( RF_TX_START == FALSE )
			{
				if ( --Times )
				{
					RF_TX_START = TRUE;
					Debug("\rTr: %d", Times);
				}
				else
				{
					State = 0;
					PIN_RF_TX_ENABLE = FALSE;
				}
			}
			break;	

		default: 
			;
	}

}

void CommandHandler_LS ( void )
{
	signed char DirName = StrToLong(&Command_Line[2]);
 
	Execute_Module_1 = Command_Processor;

	
	if ( DirName < 0 || DirName >= DIRECTORIES_COUNT )
	{
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		Debug("\nDirectory name is not exist\r");
		Debug("\n === Directory Name ===\nOWNERS_LIST 			- %d\nUSER_LIST_1 			- %d\nUSER_LIST_2 			- %d\nUSER_LIST_3 			- %d\nUSER_LIST_4 			- %d\nINP_DESCRIPT_LIST 	- %d\nRF_REMOTE_LIST    	- %d\nRF_INP_DESCRIPT_LIST - %d\nCOMMAND_MACROS       - %d\n ======================\r",

				DIRECTORY__OWNERS_LIST,
				DIRECTORY__USER_LIST_1,
				DIRECTORY__USER_LIST_2,
				DIRECTORY__USER_LIST_3,
				DIRECTORY__USER_LIST_4,
				DIRECTORY__INPUTS_DESCRIPTORS_LIST,
				DIRECTORY__RF_REMOTE_LIST,
				DIRECTORY__RF_INPUTS_DESCRIPTORS_LIST,
				DIRECTORY__COMMAND_MACROS);

		return;
	}  

	DirDescIndex = DirName;

	Debug("\n Ex_Directory[%d].Print = 0x%X", DirName, (int)Ex_Directory[DirName].Print);
	
	
	/* Dima */
	if ( Ex_Directory[DirName].Print != NULL )
	{
		Execute_Module_1 = Ex_Directory[DirName].Print;
	}
	else
	{
		Debug("\nLS: Print of this directory not supported now\r");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

/* define and set macro for command */
void CommandHandler_MS ( void )
{
	COMMAND_MACRO CmdMacro;
	unsigned char *p, s[20];
	unsigned int Result;

	Execute_Module_1 = Command_Processor;

	p = StrCpy_UpTo_Ch(s, &Command_Line[2], ' ');

	if ( p == NULL || StrLen(p) < 2 || StrLen(s) > CMD_MACRO_NAME_SIZE )
	{
	   Debug("\rMS: ERROR\r");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		return ;
	}
	else
	{
		StrCpy(CmdMacro.Name, s);
	}


	Debug("\rMacro Name: %s", CmdMacro.Name);
	Debug("\rMacro Command: %s", p);
	

	if ( DefineAndExecuteCommand(p) == TRUE )
	{
		Execute_Module_1 = Command_Processor;

		StrCpy(CmdMacro.Macro, p);

		Result = Ex_Entry_Write(LIST_COMMAND_MACROS, (unsigned char*)&CmdMacro); 
		
		if ( Result != EX_ERROR )
		{
			Debug("\nMS: ADDRESS: 0x%X", Result);
		}
		else
		{
			Debug("\nMS: WRITE - ERROR");
		}
	}
	else
	{
		Debug("\rMS: No Correct Command: %s", p);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

/* Neighbor_Cells_Control */
void CommandHandler_NC ( void )
{
	if ( Command_Line[2] == 'L' )
	{
		Neighbor_Cells_Control ( Command_Line[2] );  
	}
	else 
		if ( Command_Line[2] == 'P' )
		{
			Neighbor_Cells_Print();
		}
		else
		{
			putsf("\n\nNeighbor_Cells_Control\n NCL - learn\n NCP - print saved cells\n\n", AUX_PORT);
		}

	Execute_Module_1 = Command_Processor;
}

unsigned char EP_Timeout;

void Clear_EP ( void )
{
	if ( Time_1000ms )
	{
		if ( --EP_Timeout == 0 )
		{
			LG_LOGIN_OF_USER = FALSE;
			Special = NULL;
		}
		else
		{
			Debug(".");
		}
	}	

	
}


void CommandHandler_LG ( void )
{
	Execute_Module_1 = Command_Processor;
	
	if ( LG_LOGIN_OF_USER == TRUE )
	{
		return ;
	}
	
	StrCpy_UpTo_Ch(g_t_str, &Command_Line[4], '$');
	StrToBCD(sBCD, g_t_str, PHONE_NUMBERS_BCD_SIZE); //+1 - skip '+'
	FlipFlopN(sBCD, PHONE_NUMBERS_BCD_SIZE);


	if ( Ex_Entry_Find(LIST_USERS_GROUP_1, sBCD,0) != EX_ERROR )  
	{
		Debug("\rLogin: User login by phone: %s\r", g_t_str);
	
		EP_Timeout = 5;
		Special = Clear_EP;		  /* will be run timeout of user login command */
		LG_LOGIN_OF_USER = TRUE;
	}
	else
	{
		Debug("\n Login: User not found - Access forbiden\n");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

#define   COMMAND_EXCEPTION_AMOUNT	4
#define   COMMAND_EXCEPTION_SIZE		11

unsigned char Command_Exception[COMMAND_EXCEPTION_AMOUNT][COMMAND_EXCEPTION_SIZE] = 
{
	"",
	"",
	"",
	""
}; 

void CommandHandler_AE ( void )
{
	unsigned char i;

	Execute_Module_1 = Command_Processor;
	
	for ( i = 0; i < COMMAND_EXCEPTION_AMOUNT; i++ )
	{
		if ( Command_Exception[i][0] == 0 ) 
		{
			if ( StrLen(&Command_Line[2]) < COMMAND_EXCEPTION_SIZE )
			{
				StrCpy(Command_Exception[i],&Command_Line[2]);
				Debug("\r Cmd_AE: %d", i);
				Debug("Command_Exception[%d] = %s", i, Command_Exception[i]);
				return ;
			}		 
		} 
	}
}

unsigned char CheckForCmdException ( void )
{
	unsigned char i;

	Execute_Module_1 = Command_Processor;

	if ( StrLen(&Command_Line[2]) < TEMP_STRING_SIZE )
	{
		StrCpy(g_t_str, &Command_Line[2]);
		StrReplaceChar( g_t_str, '$', 0);
	}
	else
	{
		Debug("Cmd_AE: ERROR %d", -1);
		return 0;
	}

	for ( i = 0; i < COMMAND_EXCEPTION_AMOUNT; i++ )
	{
		if ( StrCmp(Command_Exception[i], g_t_str) == 0 )
		{
			CmdException = TRUE;
			Debug("Cmd_Excep: FOUND ");
			return TRUE;
		}		 
	}

	return 0;
}

/* Send SMS message by phone number or by list of group number */
/* Command format: SMphone_OR_List SMS_Message; */
/* Example 1. < SML1 My SMS message > - send SMS to all Users from List (group) number 1  */
/* Example 2. < SM05201234567 My SMS message N21 > - send SMS to phone: 05201234567 */
void CommandHandler_SM ( void )
{
	static unsigned char State = 0;
	/* get pointer to SMS message */
	unsigned char* p;

	switch( State )
	{
		case 0:
			Execute_Module_1 = Command_Processor;

			p = FindCharNumber(&Command_Line[2], ' ', 1);
			if ( p == NULL )
			{
				CommandHandler__Error = 22;
				return ;
			}

			*(p-1) = 0;						  /* separe */

			CommandHandler__Error = SMS_Add_Message(&Command_Line[2], p);
			
			if ( CommandHandler__Error == 0 )
			{
				State++;
				Execute_Module_1 = CommandHandler_SM;
			}
			break;


		case 1:
			if ( Tools == NULL )
			{
				/* Get result of the task */
				if ( SMS_Sender_Result != SUCCESS ) 
				{
					CommandHandler__Error = SMS_Sender_Result; 
				}
				
				State = 0;
				Execute_Module_1 = Command_Processor;
			}
			break;

		default:
			;
	}
}

void CommandHandler_SP ( void )
{
	Execute_Module_1 = Command_Processor;
	puts(&Command_Line[2], AUX_PORT);
}


void Command_Init ( void )
{
	ClearBuffer( (unsigned char*)&SMS_Packet_Receive, sizeof(SMS_Packet_Receive) ); 
	
/* 	CommandsSet[IS__SET_INPUT].CommandName = "IS"; */
/* 	CommandsSet[IS__SET_INPUT].CommandHandler = CommandHandler_IS; */

/* 	CommandsSet[IF__SET_RF_INPUT].CommandName = "IF"; */
/* 	CommandsSet[IF__SET_RF_INPUT].CommandHandler = CommandHandler_IF; */

/* 	CommandsSet[NA__ADD_NUMBER].CommandName = "NA"; */
/* 	CommandsSet[NA__ADD_NUMBER].CommandHandler = CommandHandler_NA; */

/* 	CommandsSet[SL__SHOW_LIST].CommandName = "LS"; */
/* 	CommandsSet[SL__SHOW_LIST].CommandHandler = CommandHandler_LS; */

/* 	CommandsSet[ND__DELETE_NUMBER].CommandName = "ND"; */
/* 	CommandsSet[ND__DELETE_NUMBER].CommandHandler = CommandHandler_ND; */
	
/* 	CommandsSet[LD__DELETE_LIST].CommandName = "LD"; */
/* 	CommandsSet[LD__DELETE_LIST].CommandHandler = CommandHandler_LD; */

/* 	CommandsSet[ID__DELETE_INPUT].CommandName = "ID"; */
/* 	CommandsSet[ID__DELETE_INPUT].CommandHandler = CommandHandler_ID; */
	
/* 	CommandsSet[HD__HANDSHAKE].CommandName = "##"; */
/* 	CommandsSet[HD__HANDSHAKE].CommandHandler = CommandHandler_HD; */
	
/* 	CommandsSet[ES__END_OF_SESSION].CommandName = "ES"; */
/* 	CommandsSet[ES__END_OF_SESSION].CommandHandler = CommandHandler_ES; */

/* 	CommandsSet[SU__SOFTWARE_UPDATE].CommandName = "SU"; */
/* 	CommandsSet[SU__SOFTWARE_UPDATE].CommandHandler = CommandHandler_SU; */

/* 	CommandsSet[CB__SET_CONFIG_BITS].CommandName = "CB"; */
/* 	CommandsSet[CB__SET_CONFIG_BITS].CommandHandler = CommandHandler_CB; */
	
/* 	CommandsSet[GS__GET_STATUS_FILE].CommandName = "GS"; */
/* 	CommandsSet[GS__GET_STATUS_FILE].CommandHandler = CommandHandler_GS; */

/* 	CommandsSet[TE__TECHNICAL_COMMANDS].CommandName = "TE";	 */
/* 	CommandsSet[TE__TECHNICAL_COMMANDS].CommandHandler = CommandHandler_TE; */
	
/* /\* 	CommandsSet[KE__SEND_KEY].CommandName = "KE"; *\/ */
/* /\* 	CommandsSet[KE__SEND_KEY].CommandHandler = CommandHandler_KE; *\/ */

/* /\* 	CommandsSet[DO__DISPLAY_ON].CommandName = "DO"; *\/ */
/* /\* 	CommandsSet[DO__DISPLAY_ON].CommandHandler = CommandHandler_DO; *\/ */
	
/* /\* 	CommandsSet[DF__DISPLAY_OFF].CommandName = "DF"; *\/ */
/* /\* 	CommandsSet[DF__DISPLAY_OFF].CommandHandler = CommandHandler_DF; *\/ */

/* 	CommandsSet[RF__RF_REMOTE_LEARNE_MODE].CommandName = "RF"; */
/* 	CommandsSet[RF__RF_REMOTE_LEARNE_MODE].CommandHandler = CommandHandler_RF; */

/* 	CommandsSet[OS__SET_OUTPUTS].CommandName = "OS"; */
/* 	CommandsSet[OS__SET_OUTPUTS].CommandHandler = CommandHandler_OS; */

/* 	CommandsSet[RT__RF_TRANSMIT].CommandName = "RT"; */
/* 	CommandsSet[RT__RF_TRANSMIT].CommandHandler = CommandHandler_RT; */

/* 	CommandsSet[MS__SET_MACROS].CommandName = "MS"; */
/* 	CommandsSet[MS__SET_MACROS].CommandHandler = CommandHandler_MS; */

/* 	CommandsSet[NC__NEIGHBOR_CELLS].CommandName = "NC"; */
/* 	CommandsSet[NC__NEIGHBOR_CELLS].CommandHandler = CommandHandler_NC; */

/* 	CommandsSet[LG__LOGIN_TO_PHONE].CommandName = "LG"; */
/* 	CommandsSet[LG__LOGIN_TO_PHONE].CommandHandler = CommandHandler_LG; */

/* 	CommandsSet[AE__ADD_COMMAND_EXCEPTION].CommandName = "AE"; */
/* 	CommandsSet[AE__ADD_COMMAND_EXCEPTION].CommandHandler = CommandHandler_AE; */

/* 	CommandsSet[SM__SEND_SMS_MESSAGE].CommandName = "SM"; */
/* 	CommandsSet[SM__SEND_SMS_MESSAGE].CommandHandler = CommandHandler_SM; */
	
/* 	CommandsSet[SP__SEND_TO_PORT].CommandName = "SP"; */
/* 	CommandsSet[SP__SEND_TO_PORT].CommandHandler = CommandHandler_SP; */

}

void CommandHandler_IE ( void )
{
	RC_PressedKey = StrToLong(&Command_Line[2]);
	Execute_Module_1 = Command_Processor;
}

const COMMAND_SET CommandsSet[] =
{
	{"IS", CommandHandler_IS},
	{"ID", CommandHandler_ID},
	{"IF", CommandHandler_IF},
	{"IE", CommandHandler_IE},	  /* Input Event */
	{"NA", CommandHandler_NA},
	{"LS", CommandHandler_LS},
	{"ND", CommandHandler_ND},
	{"LD", CommandHandler_LD},
	{"SU", CommandHandler_SU},
	{"GS", CommandHandler_GS},
	{"TE", CommandHandler_TE},
	{"RF", CommandHandler_RF},
	{"OS", CommandHandler_OS},
	{"MS", CommandHandler_MS},
	{"NC", CommandHandler_NC},
	{"LG", CommandHandler_LG},
	{"AE", CommandHandler_AE},
	{"SM", CommandHandler_SM},
	{"SP", CommandHandler_SP},
	{NULL,NULL}
};


void AddCommand( unsigned char SMS_Number )
{
	if ( SMS_Number )
	{
		SMS_Commands[pSMS_Commands] = SMS_Number;
		if ( ++pSMS_Commands == SMS_COMMANDS_QUEUE_MAX ) 
			pSMS_Commands = 0;
	}
}
 
unsigned char CommandHeader_Parsing( void )
{
	unsigned char FlagReg, BitNum;
	unsigned char Password[5];


	MemCpy( CommandHeader.Password, SMS_Buffer+OFFSET_PASSWORD, 4 );
	
	/* Password_Generator( Password, PhoneNumber );  */
	Password_Generator( Password, SMS_Header.Field.PhoneNumber ); 
	

	/* Check Password */
	if ( MemCmp(Password, CommandHeader.Password, 4) )  
	{
		Debug("\rPASSWORD - ERROR");	
		return FALSE;
	}

	MemCpy( (unsigned char*)&CommandHeader.Message_ID, SMS_Buffer+OFFSET_MESSAGE_ID, TYPE_INTEGER );
	CharnToHex( (unsigned char*)&CommandHeader.Message_Number, SMS_Buffer+OFFSET_MESSAGE_NUMBER, TYPE_BYTE );	
	CharnToHex( (unsigned char*)&CommandHeader.Messages_Count, SMS_Buffer+OFFSET_MESSAGES_COUNT, TYPE_BYTE );	
	
	//putsf(" ******> CommandHeader.Messages_Count = ", MODEM_PORT);
	//putch(CommandHeader.Messages_Count+'0', MODEM_PORT);
	//putch('\r', MODEM_PORT);

	//putsf(" ******> SMS_Packet_Receive.Field.Message_ID = ", MODEM_PORT);
	//putds((unsigned char*)&SMS_Packet_Receive.Field.Message_ID, 2, MODEM_PORT);
	//putch('\r', MODEM_PORT);


	if ( SMS_Packet_Receive.Field.Message_ID == 0 ) /* not packets receive */
	{
		if ( SMS_Packet_Receive.Field.Last_Message_ID != CommandHeader.Message_ID )
		{
			if ( CommandHeader.Messages_Count > 1 )
			{
				SMS_Packet_Receive.Field.Last_Message_ID = CommandHeader.Message_ID;
			}
			SMS_Packet_Receive.Field.Message_ID = CommandHeader.Message_ID;
			SMS_Packet_Receive.Field.Messages_Count = CommandHeader.Messages_Count;
		}
		else
		{
			return FALSE;
		}
	}
	else
		if ( SMS_Packet_Receive.Field.Message_ID != CommandHeader.Message_ID )
		{
			if ( !StrCmp( "ST", SMS_Buffer+OFFSET_COMMAND_NAME) || errno == 2 ) //##XXXXVA0101ST$
				return OK;		  /* SET DATE and TIME */

			return FALSE;			  /* Delete the message, because it is not in this packet */
		} 

	BitNum = CommandHeader.Message_Number -1;	/* ( -1) - not exist packet with number 0 */
	FlagReg = 0;
	if ( BitNum > 31 ) /* unsigned long  */
	{
		BitNum -= 32;  
		FlagReg++;
	}
	
	if ( READ_BIT(SMS_Packet_Receive.Data[FlagReg], BitNum) == FALSE )
	{
		SET_BIT(SMS_Packet_Receive.Data[FlagReg], BitNum);
		SMS_Packet_Receive.Field.Messages_Count--;
	}


	//SMS_Packet_Receive.Field.Timeout = SMS_PACKET_RECEIVE_TIMEOUT;
	return OK;
}
 
unsigned char DefineAndExecuteCommand ( unsigned char* ComLine )
{
	unsigned char i;
	COMMAND_MACRO CmdMacro;

	if ( StrLen(ComLine) == 0)
		return FALSE;

  FIND_COMMAND:
	
	for ( i = 0;  CommandsSet[i].CommandName != NULL;  i++ )
	{
		if ( !StrCmp(CommandsSet[i].CommandName, ComLine) || errno == 2  )
		{
 			Execute_Module_1 = CommandsSet[i].CommandHandler;
			return TRUE;
		}
	}

	StrCpy(CmdMacro.Name, ComLine);
	Debug("\rSearch macro: %s", CmdMacro.Name);
	
	
	if ( Ex_Entry_Read(LIST_COMMAND_MACROS, (unsigned char*)&CmdMacro) != EX_ERROR )
	{
		StrCpy(Command_Line, CmdMacro.Macro);
		Debug("Macro found\nCommmand Line: %s\n", Command_Line);
		goto FIND_COMMAND;
	}   
	
	Debug("\rMACRO NOT FOUND\r");
	  						 
	return FALSE;
}

unsigned char Check_ListForUser ( void )
{
	Debug("\r Search User for number: %s", SMS_Header.Field.PhoneNumber+1);

	StrToBCD(sBCD, SMS_Header.Field.PhoneNumber+1, PHONE_NUMBERS_BCD_SIZE); //+1 - skip '+'
	FlipFlopN(sBCD, PHONE_NUMBERS_BCD_SIZE);

	if ( Ex_Entry_Find(LIST_USERS_GROUP_1, sBCD,0) != EX_ERROR )  
	{
		Debug("User found\n");
		UserInList = TRUE;
		return TRUE;				  /* if phone numbr found into User Group 1 */
	}

	if (  (Command_Line[2] == CommandsSet[LG__LOGIN_TO_PHONE].CommandName[0] &&
			 Command_Line[3] == CommandsSet[LG__LOGIN_TO_PHONE].CommandName[1]) )
	{
		CommandHandler_LG();
		if ( LG_LOGIN_OF_USER == TRUE )
		{
			Debug("\rLogin: User found");
			UserInList = TRUE;
			return TRUE;				  /* access of user to phone by command EP */
		}
	}

	UserInList = FALSE;
	Debug("\rUSER NOT FOUND!\r");

	return FALSE;
}

/* 
FFFFFFFFFFFFFFFF

>>
EEPROM ADDRESS: 1080

814797232597FFFF


 */
enum
{
	CHECK_FOR_COMMANDS = 0,
	LOAD_SMS_COMMANDS_BUFFER,
	LOAD_ONE_SMS_COMMAND,
	A_COM_PORT_LOAD_COMMAND,
	/* DATA MODE */
	DATA_MODE_LOAD_COMMAND,
	DATA_MODE_SEND_ACK,
	AUX_PORT_LOAD_COMMAND
};

void Command_Processor( void )
{
	static unsigned char State = CHECK_FOR_COMMANDS, NextCommand = 0;
	unsigned char Response;
	int Offset;
	
 	//lcd_print_str("ComProc", 2,2,0);
/* 	lcd_clear_str(0,3); */
/* 	lcd_print_Number(pSMS_Commands, LEFT); */
/* 	lcd_putsf(" "); */
/* 	lcd_print_Number(SMS_Commands[pSMS_Commands], LEFT); */
/* 	lcd_putsf(" "); */
/* 	lcd_print_Number(State, LEFT); */

	switch ( State )
	{
		case CHECK_FOR_COMMANDS:						  /* Check Command sources (1.SMS;  2.Aux. ComPort) */
			if ( SYS_COMMAND )
			{
				SYS_COMMAND = FALSE;
				Command_Line = Sys_Command_Buffer;
				CommandSource = SYS_APPLICATION;
				if ( DefineAndExecuteCommand(Command_Line) == FALSE )
				{
					putsf("ER01\r\n",AUX_PORT);
					Execute_Module_1 = NULL;
					CommandSource = 0;
				}	
			}
			else
				if ( AUX_PORT_COMMAND )
				{
					CommandHandler__Error = 0;
					AUX_PORT_COMMAND = FALSE;
					CommandSource = AUX_PORT;
					Command_Line = AuxPortRecBuffer;
					if ( DefineAndExecuteCommand(Command_Line) == FALSE )
					{
						putsf("ER99\r\n",AUX_PORT);
						Execute_Module_1 = NULL;
						CommandSource = 0;
					}	
				}
				else
					/* if ( DATA_MODE_COMMAND ) */
					/* { */
					/* 	DATA_MODE_COMMAND = FALSE; */
					/* 	State = DATA_MODE_LOAD_COMMAND; */
					/* 	CommandSource = MODEM_PORT; */
					/* 	Command_Line = ModemRecBuffer; */
					/* } */
					/* else  */
						if ( pSMS_Commands ) 
						{
							Debug("\rCommand Processor: SMS command\n", 0 );
							State = LOAD_SMS_COMMANDS_BUFFER;
							Command_Line = SMS_Buffer;
						}
						else
							if ( CommandSource == AUX_PORT )
							{
								CommandSource = 0;
								
								if ( CommandHandler__Error )
								{
									printf("ER%02d\r",CommandHandler__Error);
								}
								else
								{
									putsf("NX\r\n", AUX_PORT);
								}
							}
							else
							{
								CommandSource = 0;
								Execute_Module_1 = NULL;
							}
			break;

		case DATA_MODE_SEND_ACK:
			State = CHECK_FOR_COMMANDS; 
			break;
			
		case DATA_MODE_LOAD_COMMAND:
			if ( DefineAndExecuteCommand(Command_Line) == FALSE )	/* if command not found */
			{
				State = CHECK_FOR_COMMANDS; 
				//Send_ACK("ER01");				/* ERROR - UNKNOWN COMMAND */
			}
			else
			{
				State = CHECK_FOR_COMMANDS;
			}
			break;	

		case LOAD_SMS_COMMANDS_BUFFER:
			Response = SMS_Read(SMS_Buffer, SMS_Commands[pSMS_Commands-1], BUSY_COMMAND_PROCESSOR ); 
//			putsf(">><>\r", MODEM_PORT );
			if ( Response != BUSY )
			{
				//putsf(">>NOT_BUSY\r", MODEM_PORT );
				if ( Response == TRUE )
				{
					SMS_To_Delete = SMS_Commands[--pSMS_Commands]; /* delete SMS after executing */
			
					//putsf(">>TRUE\r", MODEM_PORT );
					//puts( (LongToStr(ds, SMS_To_Delete)), MODEM_PORT);
					//putsf("\r", MODEM_PORT );
					
					if ( (CommandHeader_Parsing() == OK) || (Check_ListForUser() == TRUE) || 
						  (CheckForCmdException() == TRUE) )
					{
						if ( UserInList || CmdException )
						{
							UserInList = FALSE;
							CmdException = FALSE;
							NextCommand = 2;
						}
						else
						{
							NextCommand = OFFSET_COMMAND_NAME; /* init. pointer to first command into SMS_Buffer */
						}
						State = LOAD_ONE_SMS_COMMAND;
					}
					else
					{
						Execute_Module_1 = SMS_Command_Delete;
						State = CHECK_FOR_COMMANDS;
					}

					SMS_Packet_Receive.Field.Timeout = SMS_PACKET_RECEIVE_TIMEOUT;

					//putsf(" ****************> COMMAND_PROCESSOR == FINISH\r", MODEM_PORT );
					//State = CHECK_FOR_COMMANDS;
					//CommandProcessor_Status = NOT_BUSY;
				}
				else
				{
					putsf(" >>> SMS_READ__FALSE\r ", MODEM_PORT );
					State = CHECK_FOR_COMMANDS;
					Execute_Module_1 = NULL;
				}
			}
			break;
//##3D585o0102AP01029C01!999999 010196!888888 0202BC02!001 01014A01!09 0101DC!08$NP05443322113 76543433211 0525628459$
// AT+CMGS="0523974963",129#013####3D585o0102AP01029C01!999999 0202BC02!001 0101DC!08$$NP05443322113 76543433211 0525628459$$$1A
//AT+CMGS="0523974963",129#013####3D585o0202NP0524879210 0524853291 0523974871$$$1A
//##3D585o0102AP01029C01!999999 0202BC02!001 0101DC!08$NP05443322113 76543433211 0525628459$

		case LOAD_ONE_SMS_COMMAND:
			Offset = StrReplaceChar( Command_Line+NextCommand, '$', 0); 
			if ( Offset != (-1) )
			{
				Command_Line += NextCommand;
				if ( DefineAndExecuteCommand(Command_Line) == FALSE )	/* if command not found */
				{
					//putsf(" >>> UNKNOW COMND\r", MODEM_PORT);
					Execute_Module_1 = SMS_Command_Delete;
					State = CHECK_FOR_COMMANDS;
				}
				NextCommand = (unsigned char)Offset +1; 

				//lcd_clear_str(0, 2); 
				//lcd_putchar(Command_Line[0]);
				//lcd_putchar(Command_Line[1]);
				//lcd_putchar('-');
				//lcd_print_Number(NextCommand, LEFT);
				//delay_ms(1000);
								  
			}
			else
			{
				if ( SMS_Packet_Receive.Field.Messages_Count == 0 )
				{
					SMS_Packet_Receive.Data[0] = 0;
					SMS_Packet_Receive.Data[1] = 0;
					SMS_Packet_Receive.Data[2] = 0;
					
					putsf(" >>> SMS_PACKET_REC\r", MODEM_PORT);
				}

				Execute_Module_1 = SMS_Command_Delete;
				State = CHECK_FOR_COMMANDS;
//				CommandProcessor_Status = NOT_BUSY;
			}
			break;

		default:
			;
	}
}

